package com.small.common;

import com.small.util.PropertiesUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @create: xie
 */
public class RedisPool {
    private static JedisPool pool;//jedis连接池
    private static Integer maxTotal=PropertiesUtil.getIntegerProperty("redis.max.total",20);//最大连接数
    private static Integer maxIdle= PropertiesUtil.getIntegerProperty("redis.max.idle",10);//在jedispool中最大的idle状态（空闲的）的jedis实例的个数
    private static Integer minIdle= PropertiesUtil.getIntegerProperty("redis.min.idle",2);//在jedispool中最小的idle状态（空闲的）的jedis实例的个数
    private static Boolean testOnBorrow= PropertiesUtil.getBooleanProperty("redis.test.borrow",true);//在Borrow一个jedis实例的时候，是否进行验证操作，如果赋值为true，则得到的jedis实例肯定是可以用的
    private static Boolean testOnReturn= PropertiesUtil.getBooleanProperty("redis.test.return",true);//在Return一个jedis实例的时候，是否进行验证操作，如果赋值为true，则放回的jedis实例肯定是可以用的
    private static Integer port= PropertiesUtil.getIntegerProperty("redis1.port");//redis端口
    private static String ip= PropertiesUtil.getProperty("redis1.ip");//redisIp

    private static void initPool(){
        JedisPoolConfig config=new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);

        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);

        //连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
        config.setBlockWhenExhausted(true);

        pool=new JedisPool(config,ip,port,1000*2);
    }
    //初始化jedispool
    static {
        initPool();
    }

    //返回jedis实例
    public static Jedis getJedis(){
        return pool.getResource();
    }

    public static void returnBrokenResource(Jedis jedis){
        pool.returnBrokenResource(jedis);
    }

    public static void returnResource(Jedis jedis){
        pool.returnResource(jedis);
    }

}
